package cc.uncarbon.module.appapi.service;

import cc.uncarbon.framework.core.constant.HelioConstant;
import cc.uncarbon.framework.core.context.UserContextHolder;
import cc.uncarbon.framework.core.exception.BusinessException;
import cc.uncarbon.framework.core.page.PageParam;
import cc.uncarbon.framework.core.page.PageResult;


import cc.uncarbon.module.appapi.mapper.AppraiseMapper;
import cc.uncarbon.module.appapi.mapper.OrdersMapper;
import cc.uncarbon.module.appapi.model.request.AppraiseInsertOrUpdateDTO;
import cc.uncarbon.module.appapi.model.response.AppraiseBO;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yanrumiao.entity.AppraiseEntity;
import com.yanrumiao.entity.OrdersEntity;
import com.yanrumiao.enumns.OrdersStatusEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;


/**
 * 评价
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class AppraiseService {

    private final AppraiseMapper appraiseMapper;
    private final OrdersMapper ordersMapper;


    /**
     * 根据 ID 取详情
     *
     * @param id 主键ID
     * @return null or BO
     */
    public AppraiseBO getOneById(Long id) {
        return this.getOneById(id, false);
    }

    /**
     * 根据 ID 取详情
     *
     * @param id               主键ID
     * @param throwIfInvalidId 是否在 ID 无效时抛出异常
     * @return null or BO
     */
    public AppraiseBO getOneById(Long id, boolean throwIfInvalidId) throws BusinessException {
        AppraiseEntity entity = appraiseMapper.selectById(id);
        if (throwIfInvalidId && entity == null) {
            throw new BusinessException(400, "无效评价ID");
        }

        return this.entity2BO(entity);
    }

    /**
     * 评价-新增
     */
    @Transactional(rollbackFor = Exception.class)
    public Long adminInsert(AppraiseInsertOrUpdateDTO dto) {
        log.info("[用户-评价-新增] >> DTO={}", dto);
        this.checkExistence(dto);
        OrdersEntity orders = ordersMapper.selectById(dto.getOrderId());
        if (orders == null) {
            throw new BusinessException(400, "订单不存在");
        }
        if(orders.getStatus()!= OrdersStatusEnum.ORDER_DFW){
            throw new BusinessException(400, "订单状态异常");
        }
        orders.setStatus(OrdersStatusEnum.ORDER_YWC);
        ordersMapper.updateById(orders);


        dto.setId(null);
        AppraiseEntity entity = new AppraiseEntity();
        entity.setUserId(UserContextHolder.getUserId());
        BeanUtil.copyProperties(dto, entity);

        appraiseMapper.insert(entity);

        return entity.getId();
    }

    /**
     * 用户-编辑
     */
    @Transactional(rollbackFor = Exception.class)
    public void adminUpdate(AppraiseInsertOrUpdateDTO dto) {
        log.info("[用户-评价-编辑] >> DTO={}", dto);
        this.checkExistence(dto);

        AppraiseEntity entity = new AppraiseEntity();
        BeanUtil.copyProperties(dto, entity);

        appraiseMapper.updateById(entity);
    }

    /**
     * 用户-删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void adminDelete(Collection<Long> ids) {
        log.info("[用户-评价-删除] >> ids={}", ids);
        appraiseMapper.deleteBatchIds(ids);
    }


    /*
    ----------------------------------------------------------------
                        私有方法 private methods
    ----------------------------------------------------------------
     */

    /**
     * 实体转 BO
     *
     * @param entity 实体
     * @return BO
     */
    private AppraiseBO entity2BO(AppraiseEntity entity) {
        if (entity == null) {
            return null;
        }

        AppraiseBO bo = new AppraiseBO();
        BeanUtil.copyProperties(entity, bo);

        // 可以在此处为BO填充字段

        return bo;
    }

    /**
     * 实体 List 转 BO List
     *
     * @param entityList 实体 List
     * @return BO List
     */
    private List<AppraiseBO> entityList2BOs(List<AppraiseEntity> entityList) {
        if (CollUtil.isEmpty(entityList)) {
            return Collections.emptyList();
        }

        // 深拷贝
        List<AppraiseBO> ret = new ArrayList<>(entityList.size());
        entityList.forEach(
                entity -> ret.add(this.entity2BO(entity))
        );

        return ret;
    }

    /**
     * 实体分页转 BO 分页
     *
     * @param entityPage 实体分页
     * @return BO 分页
     */
    private PageResult<AppraiseBO> entityPage2BOPage(Page<AppraiseEntity> entityPage) {
        return new PageResult<AppraiseBO>()
                .setCurrent(entityPage.getCurrent())
                .setSize(entityPage.getSize())
                .setTotal(entityPage.getTotal())
                .setRecords(this.entityList2BOs(entityPage.getRecords()));
    }

    /**
     * 检查是否已存在同名数据
     *
     * @param dto DTO
     */
    private void checkExistence(AppraiseInsertOrUpdateDTO dto) {
        /*
        可以根据自己业务需要，解禁这段代码，修改判断条件和文案
*/
        LambdaQueryWrapper<AppraiseEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AppraiseEntity::getOrderId, dto.getOrderId());
        AppraiseEntity existingEntity = appraiseMapper.selectOne(queryWrapper);

        if (existingEntity != null && !existingEntity.getId().equals(dto.getId())) {
            throw new BusinessException(400, "已存在相同评价，请重新输入");
        }

    }

}
